<?php
class Page_model extends CI_Model
{	
	function __construct()
	{
		parent::__construct();
		
	}
	private function _required($required, $data)
	{
		foreach($required as $field) if(!isset($data[$field])) return false;
		return true;
	}
	
	private function _default($defaults, $options)
	{
		return array_merge($defaults, $options);
	}
	
	function insert($options = array())
	{
		//if(!$this->_required(array(.$qualification_fields.), $options)) 
		//		return false;
	
		//$options = $this->_default(array('u_created_on' => sql_current_datetime()), $options);
		$qualificationArray = array('page_id', 'page_created', 'page_modified', 'layout', 'widgets', 'page_parent', 'page_name', 'order', 'url');
		foreach($qualificationArray as $qualifier)
			if(isset($options[$qualifier])) 
				$this->db->set($qualifier, $options[$qualifier]);
	 
		$this->db->insert('pages');
	
		return $this->db->insert_id();
	}
	
	function update($options = array())
	{
		if(!$this->_required(array('page_id'), $options)) 
			return false;

		$qualificationArray = array('page_id', 'page_created', 'page_modified', 'layout', 'widgets', 'page_parent', 'page_name', 'order', 'url');
		foreach($qualificationArray as $qualifier)
			if(isset($options[$qualifier])) 
				$this->db->set($qualifier, $options[$qualifier]);
	
		$this->db->where('page_id', $options [ 'page_id' ]);	
		$this->db->update('pages');	
		return $this->db->affected_rows();
	}
	
	function get($options = array())
	{
		$options = $this->_default(array('sort_direction' => 'asc'), $options);
	
		$qualificationArray = array('page_id', 'page_created', 'page_modified', 'layout', 'widgets', 'page_parent', 'page_name', 'order', 'url');
		foreach($qualificationArray as $qualifier)
			if(isset($options[$qualifier])) 
				$this->db->where($qualifier, $options[$qualifier]);
	
		if(isset($options ['limit']) && isset($options ['offset'])) 
			$this->db->limit($options ['limit'], $options ['offset']);
		else if(isset($options ['limit'])) 
			$this->db->limit($options ['limit']);
	
		if(isset($options ['sort_by'])) 
		$this->db->order_by($options ['sort_by'], $options ['sort_direction']);
		
		$query = $this->db->get('pages');
		
		if($query->num_rows() == 0) 
			return false;
	
		if(isset($options ['page_id']))
			return $query->row_array(0);
		else
			return $query->result_array();
	}
	
	function delete($options = array())
	{
		if(!$this->_required(array('page_id'), $options)) 
			return false;   
    
        $page = $this->page_model->get(array('page_id' => $options['page_id']));
            
        // Give the children a new parent
        $childs = $this->page_model->get(array('page_parent' => $id));
        foreach($childs as $child)
        {
            $this->db
                ->where('page_parent', $page['page_id'])
                ->set('page_parent', $page['page_parent'])
                ->update('pages');
        }
        
		$this->db->where('page_id', $options ['page_id']);
		$this->db->delete('pages');
	}

	function sorting_update($sort)
	{
		// Get the root out of array first, no need for it
		// $root = $sort[0];
		unset($sort[0]);
		$sort = array_values($sort);
		
		for($i = 0; $i < count($sort); $i++)
		{
			$update = array('page_id'		=> $sort[$i]['dbid'],
							'order'	=> $i);
							
			if(isset($sort[$i]['parent_dbid']))
				$update['m_m_id'] = $sort[$i]['parent_dbid'];
			else
				$update['m_m_id'] = 0;
				
			$this->update($update);
		}
	}

	public function get_page_list()
	{
		$pages = $this->db->select('page_id, page_parent, page_name')->from('pages')->get();
		if($pages->num_rows() == 0)
			return FALSE;
		else
			return $pages->result_array();
		
	}
	
	public function save_routes()
	{
		$routes = $this->get();
		if ( !empty( $routes ) )
		{
			foreach( $routes as $route )
			{
				$data[] = '$route["' . $this->get_route($route['page_id']) . '"] = "' . "page/view/{$route['page_id']}" . '";';
			}
	 
			$output = implode("\n", $data);
	 
			$this->load->helper('file');
			write_file(APPPATH . "cache/page_routes.php", '<?php ' . $output . ' ?>');
		}
	}
	 
	public function get_route($id)
	{
		$page = $this->get(array('page_id' => $id));
	 
		if($page["page_parent"] != 0)
				$prefix = $this->get_route($page["page_parent"])."/".$page['url'];
		else
				$prefix = $page['url'];
	 
		return $prefix;
	}		
	
	public function get_page($id)
	{
		$page = $this->get(array('page_id' => $id));
		if( ! $page)
			return FALSE;

		$this->load->model('content_model');
		$this->load->model('widget_model');
		$this->load->library('tree');	
		$site_config 				= $this->display->get_theme_config('site');	
		$tree						= $this->tree->rows_to_tree($this->page_model->get_page_list(), 'page_id', 'page_parent');	
		
		// General
		$data['page'] 				= $page;		
		$data['layouts']	 		= $site_config['page_layouts'];
		$data['pages_options_list']	= $this->tree->tree_to_options($tree, 'page_name', 'page_id');
		
		// Route
		$data['route']				= $this->get_route($id);
		
		// Widgets
		$data['widget_areas'] 		= $this->display->get_layout_widget_areas($page['layout']);
		$used_widgets				= json_decode($data['page']['widgets']);
		$data['widgets']  			= $this->widget_model->get();
        
     
        
        // FOAUT FOUT FOUT, zo krijg je tuurlijk niet alle widget areas te zien
        // maar allen de used widgets, dus als je niks selecteerd als widget
        // ben je volgens mij fucked. Heeft ook te maken met page_edit.tpl widget
        // select box code. Dit probleem is core to the bone en moet aangepakt worden
		for($i = 0; $i < count($data['widgets']); $i++)
		{
			if(isset($used_widgets))
				foreach($used_widgets as $area => $widget)
				{
					if($data['widgets'][$i]['id'] == (int) $widget)
					{
						$data['widgets'][$i]['used'] = TRUE;
						$data['widgets'][$i]['area'] = $area;
					}
				}
		}
		
			
		// Languages & Content	
		$contents 					= $this->content_model->get(array('page_id'  => $id));			
		$used_languages 	= array();	
		if($contents)
			foreach($contents as $content)
			{
				if(!in_array($content['language'], $used_languages))
				{
					$used_languages[] = $content['language'];
					$data['contents'][$content['language']] = $content;
				}
				
			}
		$data['used_languages'] = $used_languages;
		
			
		foreach($this->config->item('site_supported_languages') as $lang)
		{
			$data['languages'][] = array('name' 	=> $lang, 
										 'enabled' 	=> in_array($lang, $used_languages)
										 );
		}
		
		return $data;	
	}	
}